export class FixedLengthQueue {
  constructor(length) {
    this.length = length;
    this.queue = new Array(length);
    this.head = 0;
    this.tail = 0;
    this.size = 0;
  }

  // 向队列中添加一个元素
  enqueue(element) {
    if (this.size === this.length) {
      this.head = (this.head + 1) % this.length; // 如果队列已满，将头部移动到下一个位置
    } else {
      this.size++;
    }
    this.queue[this.tail] = element;
    this.tail = (this.tail + 1) % this.length;
  }

  // 从队列中移除一个元素并返回它
  dequeue() {
    if (this.isEmpty()) return undefined;
    const element = this.queue[this.head];
    this.queue[this.head] = undefined;
    this.head = (this.head + 1) % this.length;
    this.size--;
    return element;
  }

  // 检查队列是否为空
  isEmpty() {
    return this.size === 0;
  }

  // 返回队列的大小
  getSize() {
    return this.size;
  }

  // 返回队列中的所有元素
  getAllElements() {
    const elements = [];
    let current = this.head;
    for (let i = 0; i < this.size; i++) {
      elements.push(this.queue[current]);
      current = (current + 1) % this.length;
    }
    return elements;
  }

  // 清空队列
  clearAll() {
    this.queue.fill(undefined);
    this.head = 0;
    this.tail = 0;
    this.size = 0;
  }
}
